/** JuST4it */
const fs = require('fs')
const moment = require('moment');

class WebpackComplierVersionPlugin {
  constructor(options) {
    this.options = options || { path: './package.json',format: 'YYYYMMDDHHmmss' }
  }

  apply(compiler) {
    const _path = this.options.path
    const _format = this.options.format
    // eslint-disable-next-line node/no-deprecated-api
    fs.exists(_path, function(exists) {
      let _obj = {}
      if (exists) {
        try {
          _obj = JSON.parse(fs.readFileSync(_path))
        } catch (e) {}
      }
      _obj.build =  moment().format(_format)
      fs.writeFileSync(_path, JSON.stringify(_obj, null, '\t'))
    })
  }
}

module.exports = WebpackComplierVersionPlugin
